package com.uchengwang.ui.cm_ui.ucity.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.RyConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.rychat.bean.InviteUserBean;
import com.uchengwang.ui.cm_ui.rychat.bean.RyUserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.cm_ui.ucity.adapter.ApplyAdapter;
import com.uchengwang.ui.cm_ui.ucity.listener.GetApplyListBeanListener;
import com.uchengwang.ui.cm_ui.ucity.presenter.HttpCityPresenter;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.model.Conversation;

/**
 * Created by U城网 on 2017/8/10.
 * 处理报名
 */

public class ApplyNewActivity extends BaseWithTitleActivity implements View.OnClickListener{
    private RecyclerView apply_rv;
    private ApplyAdapter adapter;
    private LinearLayout bm_linear;
    private TextView apply_create, agreeyes_all;//创建群组

    private AppCompatCheckBox agreeyes_box;
    private List<UserBean> list;
    private long uid, id;//信息发布人的ID, 信息的ID

    private int page = 1;//当前页  每页请求多少数据
    private int totlaPagers ;//总页数【服务器返回】
    private PtrClassicFrameLayout agreeYes_refresh;
    private RecyclerAdapterWithHF mAdapter;
    private boolean isAllCheck = false;//是不是全选
    private int allCount;//选择的总人数
    private String groupName, groupLogo;
    private List<RyUserBean> memmbers;//群成员
    private String pubTitle;
    private boolean isAllow = true;
    private List<UserBean> checkList;
    private long groupId;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //点击增减
                    boolean isCheck = (boolean) msg.obj;
                    if (isAllCheck){
                        if (isCheck){
                            allCount++;
                            agreeyes_all.setText("全选 "+allCount);
                        }else {
                            allCount--;
                            if (allCount <=0){
                                agreeyes_all.setText("全选");
                                agreeyes_box.setChecked(false);
                            }else {
                                agreeyes_all.setText("全选 "+allCount);
                            }
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_agree_yes);
        setTitle("报名");

        initView();
    }

    private void initView() {
        agreeYes_refresh = (PtrClassicFrameLayout) findViewById(R.id.agreeYes_refresh);

        apply_rv = (RecyclerView) findViewById(R.id.fm_agreeyes_rv);
        bm_linear = (LinearLayout) findViewById(R.id.fm_agreeyes_bottom);

        agreeyes_box = (AppCompatCheckBox) findViewById(R.id.fm_agreeyes_box);
        agreeyes_all = (TextView) findViewById(R.id.fm_agreeyes_all);

        apply_create = (TextView) findViewById(R.id.fm_agreeyes_agree);//创建群聊

        apply_create.setOnClickListener(this);

        initData();

    }

    private void initData() {
        uid = getIntent().getLongExtra(BaseConfig.UID, 0);
        id = getIntent().getLongExtra(BaseConfig.ID, 0);
        groupName = getIntent().getStringExtra(BaseConfig.GROUP_NAME_UCW);
        pubTitle = getIntent().getStringExtra(BaseConfig.PUB_TITLE);
        groupId = getIntent().getLongExtra(BaseConfig.GROUP_ID, 0);
        groupLogo = getIntent().getStringExtra(BaseConfig.GROUP_LOGO);

        agreeyes_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                LoadingUtils.getUtils().loading(ApplyNewActivity.this);
                if (b){
                    isAllCheck = true;
                    //全部选中
                    list = adapter.getData();
                    allCount = 0;
                    if (list != null && list.size()>0){
                        for (UserBean bean : list){
                            if (!adapter.isMember(bean.getId())){
                                bean.setCheck(true);
                                allCount++;
                            }
                        }
                        agreeyes_all.setText("全选 "+allCount);
                        agreeyes_all.setTextColor(getResources().getColor(R.color.ustudy_no_choose));
                        adapter.notifyDataSetChanged();
                    }
                }else {
                    isAllCheck = false;
                    //取消全选
                    if (list != null && list.size()>0){
                        for (UserBean bean : list){
                            bean.setCheck(false);
                        }
                        agreeyes_all.setText("全选");
                        agreeyes_all.setTextColor(getResources().getColor(R.color.comment_color));
                        adapter.notifyDataSetChanged();
                    }
                }
                LoadingUtils.getUtils().hide();
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(this);
        if (uid == UCommonUtil.getUtil().getId()){//信息时自己发布的
            adapter = new ApplyAdapter(this, true);
            bm_linear.setVisibility(View.VISIBLE);
        }else {
            adapter = new ApplyAdapter(this, false);
        }
        adapter.setHandle(handler);
        apply_rv.setLayoutManager(manager);
        mAdapter = new RecyclerAdapterWithHF(adapter);
        apply_rv.setAdapter(mAdapter);

        agreeYes_refresh.setAutoLoadMoreEnable(true);
        agreeYes_refresh.setLoadMoreEnable(true);

        agreeYes_refresh.postDelayed(new Runnable() {

            @Override
            public void run() {
                agreeYes_refresh.autoRefresh(true);
            }
        }, 150);

        agreeYes_refresh.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                page = 1;
                agreeYes_refresh.loadMoreComplete(true);
                getApplys(true);
            }
        });

        agreeYes_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                page++;
                if (page <= totlaPagers){
                    //当前请求页大于总页数，不再请求
                    getApplys(false);
                } else {
                    agreeYes_refresh.loadMoreComplete(false);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (groupId <1){
            //说明没创建过群
            apply_create.setText("创建群聊");
        }else {
            apply_create.setText("邀请入群");
        }

        if (BaseConfig.isRelease){
            agreeYes_refresh.postDelayed(new Runnable() {

                @Override
                public void run() {
                    agreeYes_refresh.autoRefresh(true);
                }
            }, 150);
        }
    }

    /**
     * 获取报名人数信息
     * */
    private void getApplys(final boolean isRefresh){
        HttpCityPresenter.getPresenter().getApplyInfos(this, id, page, 10, null,  new GetApplyListBeanListener() {
            @Override
            public void onResult(int status, int allPagers, int total, String msg, List<UserBean> data) {
                if (isRefresh){
                    agreeYes_refresh.refreshComplete();
                }else {
                    agreeYes_refresh.loadMoreComplete(true);
                }
                if (status != 0 || data == null){
                    return;
                }
                totlaPagers = allPagers;

                if (isRefresh){
                    adapter.setData(data);
                }else {
                    adapter.getData().addAll(data);
                    adapter.notifyDataSetChanged();
                }
                //获取到群成员
                if (memmbers == null || BaseConfig.isRelease){
                    getGroupInfo();
                }else {
                    adapter.setMembers(memmbers);
                }
                if (adapter.getData() != null && adapter.getData().size() >0 && uid ==UCommonUtil.getUtil().getId()){
                    bm_linear.setVisibility(View.VISIBLE);//建群暂时取消
                }


            }
        });
    }

    /**
     * 调取环信的接口,获取群组信息
     * */
    private void getGroupInfo(){
        if (groupId <1){
            return;
        }
        RyGroupManager.getManager().getGroupMembers(this, groupId, 1, 999, new OnHttpResultListener<RyUserBean>() {
            @Override
            public void onResult(int status, String msg, int total, List<RyUserBean> list) {
                if (list == null || list.size() <1){
                    return;
                }
                memmbers = list;
                if (memmbers != null && memmbers.size() >0){
                    adapter.setMembers(memmbers);
                }
            }
        });

    }

    private String[] mems;
    @Override
    public void onClick(View view) {
        //将选择的用户带到下个界面
        List<UserBean> beans = adapter.getData();
        checkList = new ArrayList<>();
        for (UserBean b : beans){
            if (b.isCheck()){
                checkList.add(b);
            }
        }

        if (checkList != null && checkList.size() >0){
            int count = checkList.size();
            mems = new String[count];
            for (int i=0;i <count; i++){
                mems[i] = String.valueOf(checkList.get(i).getId());
            }
        }else {
            UCommonUtil.getUtil().showToast(this, "请选择");
            return;
        }
        switch (view.getId()){
            case R.id.fm_agreeyes_agree://创建群聊
                if (groupId <1){
                    //创建群
                    if (!isAllow){
                        return;
                    }
                    create();
                    isAllow = false;
                }else {
                    //邀请加入
                    LoadingUtils.getUtils().loading(this);
                    addMembers();
                }
                break;
        }
    }

    /**
     * 创建群 拉入群
     * */
    private void create(){
        if (UCommonUtil.getUtil().isNeedLogin(this, false)){
            return;
        }

        LoadingUtils.getUtils().loading(this);
        IHttpManager.RequestMethod method = null;
        String url = "";

        MapRequest map = new MapRequest();
        map.put(BaseConfig.GROUP_NAME_UCW, pubTitle+"交流群");
        map.put(BaseConfig.IS_PUBLIC, true);
        map.put(BaseConfig.USER_LIMIT, 500);
        map.put(BaseConfig.IS_NEED_APPLY, false);
        map.put(BaseConfig.GROUP_DESC, pubTitle+"交流群");
        if (!TextUtils.isEmpty(groupLogo)){
            map.put(BaseConfig.GROUP_LOGO, groupLogo);
        }else {
            map.put(BaseConfig.GROUP_LOGO, BaseConfig.ShortTimeLogo);
        }
//        map.put(BaseConfig.REFER_TYPE, pubType);//1.Publish群; 2.好友群; 3.社团群; 4.校吧群; 5.班级群; 6.纳新群

        map.put(BaseConfig.REFER_ID, id);
        map.put(BaseConfig.MEMBER_ROLE, BaseConfig.STUDENT_ROLE);

        map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);

        map.put(BaseConfig.CREATE_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.CREATE_UID, UCommonUtil.getUtil().getId());

        map.put(BaseConfig.ADMIN_NICK_NAME, UChengApplication.nickName);
        map.put(BaseConfig.ADMIN_UID, UCommonUtil.getUtil().getId());

        method = RyConfig.PublishGroup.method;
        url =  RyConfig.PublishGroup.URL;


        if (mems != null && mems.length >0){
            map.put(BaseConfig.USER_IDS, mems);
        }


        HttpManager.newInstance(this).query(method, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                isAllow = true;
                UCommonUtil.getUtil().showToast(ApplyNewActivity.this, "创建失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "status="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                isAllow = true;
                if (status ==0 ){
                    UCommonUtil.getUtil().showToast(ApplyNewActivity.this, "创建成功");
                    if (!TextUtils.isEmpty(data)){
//                        UCity3Activity.groupId = Long.parseLong(data);//U城活动群
                        BaseConfig.isRelease = true;
                        UCommonUtil.getUtil().toChatActiviy(ApplyNewActivity.this, data, Conversation.ConversationType.GROUP, pubTitle+"交流群");

                        ApplyNewActivity.this.finish();
                    }
                    return;
                }
                UCommonUtil.getUtil().showToast(ApplyNewActivity.this, msg);
            }
        });

    }

    /**
     * 如果从上个界面带过来的数据不为空 再将这些人邀请加群
     * */
    private void addMembers(){
        if (checkList == null || checkList.size() <1){
            return;
        }

        List<InviteUserBean> userBeanList = new ArrayList<>();
        for (UserBean userBean : checkList){
            //选中邀请的好友
            InviteUserBean inviteUserBean = new InviteUserBean();
            inviteUserBean.setGroupId(groupId);
            inviteUserBean.setGroupName(groupName);
            inviteUserBean.setInviteMsg("欢迎您");
            inviteUserBean.setToUid(userBean.getId());
            inviteUserBean.setToNickName(userBean.getNickName());
            inviteUserBean.setToUserAvatar(userBean.getUserAvatar());

            userBeanList.add(inviteUserBean);
        }

        RyGroupManager.getManager().inviteMember(this, userBeanList, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                LoadingUtils.getUtils().hide();
                if (stutas ==0){
                    UCommonUtil.getUtil().showToast(ApplyNewActivity.this, "邀请成功");
                    BaseConfig.isRelease  = true;
                    agreeYes_refresh.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            agreeYes_refresh.autoRefresh(true);
                        }
                    }, 150);
                }else {
                    UCommonUtil.getUtil().showToast(ApplyNewActivity.this, "邀请失败, 请重试");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
